package com.pts.dao;



import com.pts.db.DbUtils;
import com.pts.vo.Product;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ProductDao extends GenericDao {
    @Override
    public Product findByCard(String card) {
        Product product = null;
        ResultSet resultSet;
        DbUtils du = new DbUtils();
        Connection connection = du.getConn();
        String sql="select pid,tid,name,state,img from product where card=?";
        try {
            PreparedStatement preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,card);
            resultSet = preparedStatement.executeQuery();
            if(!resultSet.next()){
                resultSet.close();
                preparedStatement.close();
                System.out.println("resultSet为空");
                return null;
            }
            product = new Product();
            product.setPid(resultSet.getInt("pid"));
            product.setTid(resultSet.getByte("tid"));
            product.setName(resultSet.getString("name"));
            product.setState(resultSet.getByte("state"));
            product.setImg(resultSet.getString("img"));
            resultSet.close();
            preparedStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return product;
    }
    @Override
    public boolean add(Object obj){
        Product product = (Product)obj;
        DbUtils du = new DbUtils();
        Connection connection = du.getConn();
        String sql = "insert into product(name,pid,card,tid,state,img) values (?,?,?,?,?,?)";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, product.getName());
            preparedStatement.setString(2,String.valueOf(product.getPid()) );
            preparedStatement.setString(3,product.getCard() );
            preparedStatement.setString(4,String.valueOf(product.getTid()) );
            preparedStatement.setString(5,String.valueOf(product.getState()) );
            preparedStatement.setString(6,product.getImg() );
            if(preparedStatement.executeUpdate()==0){
                preparedStatement.close();
                return false;
            }
            preparedStatement.close();
        }
        catch (SQLException e){
            e.printStackTrace();
        }
        return true;
    }
}
